import * as vscode from 'vscode';
import { Memory } from '../memory';
import * as fs from 'node:fs/promises';

export namespace Helper {
  export async function workspace(): Promise<vscode.WorkspaceFolder>;
  export async function workspace(uri: vscode.Uri): Promise<vscode.WorkspaceFolder>;
  export async function workspace(name: string): Promise<vscode.WorkspaceFolder>;
  export async function workspace(idx: number): Promise<vscode.WorkspaceFolder>;
  export async function workspace(arg0: any = 0): Promise<vscode.WorkspaceFolder> {
    const workspaces = vscode.workspace.workspaceFolders;
    let workspace: vscode.WorkspaceFolder | undefined = undefined;
    if (typeof arg0 === 'number') {
      workspace = workspaces?.at(arg0);
    } else if (typeof arg0 === 'string') {
      workspace = workspaces?.find(v => v.name === arg0);
    } else if (arg0 instanceof vscode.Uri) {
      workspace = workspaces?.find(v => v.uri.toString() === arg0.toString());
    }
    if (!workspace) {
      throw new Error("未打开工作空间");
    }
    return workspace;
  };

  export function fsPath(uri: vscode.Uri): string {
    return uri.fsPath.replace(/\\/g, '/');
  }

  export async function activeTsDocument(): Promise<[vscode.TextDocument, vscode.TextEditor]> {
    const textEditor = vscode.window.activeTextEditor;
    const document = textEditor?.document;
    if (!textEditor) {
      throw new Error("活动的文本编辑器不存在");
    } else if (document?.uri.scheme !== 'file') {
      throw new Error('当前文本编辑器的文档类型不是file');
    } else if (!document.uri.fsPath.match(/\.(ts|tsx|js|jsx|vue)$/)) {
      throw new Error('目前只支持ts/tsx/js/jsx/vue文件');
    }
    return [document, textEditor];
  }

  export interface PackageInfo {
    version?: string;
  }
  export async function packageInfo(): Promise<PackageInfo> {
    const diskPath = vscode.Uri.joinPath(Memory.context().extensionUri, 'package.json');
    const result = await fs.readFile(diskPath.fsPath).then(v => v.toString()).then(JSON.parse);
    return result;
  }
}